package com.sq.partner.manager.service.impl;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.dao.HaidaInfoDao;
import com.sq.partner.manager.dao.HaidaStageInfoDao;
import com.sq.partner.manager.dao.IGatewayPolicyDao;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.HaidaInfo;
import com.sq.partner.manager.mybatis.model.HaidaStageInfoVo;
import com.sq.partner.manager.service.HaidaService;
import com.sq.partner.manager.util.FreeMarkerUtil;
import com.sq.partner.manager.util.HttpConnectorUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author lxy
 * 2022/4/2 11:42
 */
@Service
public class HaidaServiceImpl implements HaidaService {
	
	private final Logger logger = LogUtil.getLog(HaidaServiceImpl.class);
	
	@Resource
	private HaidaInfoDao haidaInfoDao;
	
	@Resource
	private HaidaStageInfoDao haidaStageInfoDao;
	
	@Resource
	private IGatewayPolicyDao iGatewayPolicyDao;
	
	@Override
	public Page queryHaidaInfoPage(Map<String, Object> map) throws Exception {
		Page page = beforeQueryHaidaPolicy(map);
		return haidaInfoDao.queryHaidaReconciliationPage(page);
	}
	
	@Override
	public List<HaidaInfo> queryHaidaInfoList(Map<String, Object> map) throws Exception {
		return haidaInfoDao.queryHaidaReconciliationList(map);
	}
	
	@Override
	public long queryHaidaReconciliationCount(Map<String, Object> map) throws Exception {
		if (map.containsKey("startTransDate") && map.containsKey("endTransDate")) {
			String start = (String) map.get("startTransDate");
			String end = (String) map.get("endTransDate");
			if (start != null && !start.equals("")) {
				map.put("startTransDate", start + " 00:00:00");
			}
			if (end != null && !end.equals("")) {
				map.put("endTransDate", end + " 23:59:59");
			}
		}
		return haidaInfoDao.queryHaidaReconciliationCount(map);
	}
	
	public Page beforeQueryHaida(Map<String, Object> haidaMap) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat();
		Page page = new Page();
		Map<String, Object> map = new HashMap<String, Object>();
		if (haidaMap.get("pageIndex") != "-1") {
			page.setCurrent((Integer) haidaMap.get("pageIndex"));
			map = SqlUtil.buildPageMap(page);
		}
		// 交易时间加上时间方便SQL中比较
		if (haidaMap.containsKey("startTransDate") && haidaMap.containsKey("endTransDate")) {
			String start = (String) haidaMap.get("startTransDate");
			String end = (String) haidaMap.get("endTransDate");
			if (start != null && !start.equals("")) {
				haidaMap.put("startTransDate", start.replaceAll("-", ""));
			}
			if (end != null && !end.equals("")) {
				haidaMap.put("endTransDate", end.replaceAll("-", ""));
			}
		}
		
		map.putAll(haidaMap);
		page.setType(map);
		return page;
	}
	public Page beforeQueryHaidaPolicy(Map<String, Object> haidaMap) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat();
		Page page = new Page();
		Map<String, Object> map = new HashMap<String, Object>();
		if (haidaMap.get("pageIndex") != "-1") {
			page.setCurrent((Integer) haidaMap.get("pageIndex"));
			map = SqlUtil.buildPageMap(page);
		}
		// 交易时间加上时间方便SQL中比较
		if (haidaMap.containsKey("startTransDate") && haidaMap.containsKey("endTransDate")) {
			String start = (String) haidaMap.get("startTransDate");
			String end = (String) haidaMap.get("endTransDate");
			if (start != null && !start.equals("")) {
				haidaMap.put("startTransDate", start + " 00:00:00");
			}
			if (end != null && !end.equals("")) {
				haidaMap.put("endTransDate", end + " 23:59:59");
			}
		}
		
		map.putAll(haidaMap);
		page.setType(map);
		return page;
	}
	/**
	 * 调用保单终止接口
	 *
	 * @param map serialNumber：流水号，orderNo订单号，polNo：保单号；
	 * @throws Exception -
	 */
	public Map<String, String> terminationOfThePolicy(Map<String, Object> map) throws Exception {
		GatewayPolicy gatewayPolicy = iGatewayPolicyDao.queryNocarPolicyInfoByPolNo((String) map.get("polNo"));
		// 合作伙伴代码
		String partnerCode = gatewayPolicy.getPartnerNo();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		// 交易时间
		String transDate = sdf.format(date);
		map.put("partnerCode", partnerCode);
		map.put("transDate", transDate);
		String requestXml = "";
		String responseXml = "";
		requestXml = FreeMarkerUtil.process("/app/nocar/P1033.ftl", map);
		logger.info("交易系统请求报文：\n" + requestXml);
		responseXml = HttpConnectorUtil.interaction(Config.getProp("NOCAR.TRANS.URL"), requestXml, partnerCode, Constants.GW_CH_TX_P1033);
		logger.info("交易系统返回报文：\n" + responseXml);
		// 处理返回报文
		Document document = DocumentHelper.parseText(responseXml);
		Element root = document.getRootElement();
		String resultCode = selectSingleNodeByRoot(root, "/INSUREQRET/HEAD/RESULTCODE");
		String resultInfo = selectSingleNodeByRoot(root, "/INSUREQRET/HEAD/ERRINFO");
		Map<String, String> resultMap = new HashMap<String, String>();
		if ("".equals(resultCode) || resultCode.length() != 4 || !"0000".equals(resultCode)) {
			// 预期之外的返回值
			resultCode = "9999";
		}
		if ("0000".equals(resultCode)) {
			resultMap.put("resultCode", resultCode);
		} else {
			resultInfo = "".equals(resultInfo) ? "交易失败" : resultInfo;
		}
		resultMap.put("resultInfo", resultInfo);
		return resultMap;
	}
	
	@Override
	public List<HaidaStageInfoVo> queryHaidaStageInfoList(Map<String, Object> map) throws Exception {
		return haidaStageInfoDao.queryHaidaStageInfoList(map);
	}
	
	@Override
	public Page queryHaidaStageInfoPage(Map<String, Object> map) throws Exception {
		Page page = beforeQueryHaida(map);
		return haidaStageInfoDao.queryHaidaStagePage(page);
	}
	
	/**
	 * 对节点内容判空操作
	 *
	 * @param root 根节点
	 * @param path 节点path
	 * @return 节点内容
	 */
	private String selectSingleNodeByRoot(Element root, String path) {
		Node node = root.selectSingleNode(path);
		return node == null ? "" : node.getText();
	}
	
	@Override
	public HSSFWorkbook generateHssWorkBook(String sheetName, int columnNumber, int[] columnWidth,
	                                        String[] columnName, String[][] haidaInfos) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		for (int i = 0; i < columnNumber; i++) {
			sheet.setColumnWidth(i, columnWidth[i] * 256);
		}
		HSSFRow headerRow = sheet.createRow(0);
		// 第"0"行行高设置为40
		headerRow.setHeightInPoints(40);
		// 表头单元格样式
		HSSFCellStyle headerStyle = wb.createCellStyle();
		// 设置自动换行
		headerStyle.setWrapText(true);
		// 居中样式
		headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		headerStyle.setBottomBorderColor(HSSFColor.BLACK.index);
		headerStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
		headerStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
		headerStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
		headerStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		// 设置表头字体样式
		HSSFFont headerFont = wb.createFont();
		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setFontName("宋体");
		// 设置字体大小 
		headerFont.setFontHeightInPoints((short) 10);
		headerStyle.setFont(headerFont);
		
		HSSFCell cell = null;
		for (int i = 0; i < columnNumber; i++) {
			cell = headerRow.createCell(i);
			cell.setCellValue(columnName[i]);
			cell.setCellStyle(headerStyle);
		}
		HSSFRow row = null;
		// 数据的样式
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		style.setBottomBorderColor(HSSFColor.BLACK.index);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		HSSFFont font = wb.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		style.setFont(font);
		for (int i = 0; i < haidaInfos.length; i++) {
			row = sheet.createRow(i + 1);
			for (int j = 0; j < columnNumber; j++) {
				cell = row.createCell(j);
				row.setHeightInPoints(16);
				cell.setCellValue(haidaInfos[i][j]);
				cell.setCellStyle(style);
			}
		}
		return wb;
	}
}
